package com.suxin.oci.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author Tang
 * @classname SupplyStatisticsDataSourceConfig
 * @description [ 供气统计数据源 ]
 * @date 2021/4/24 18:31
 */
@Configuration
@MapperScan(basePackages = {"com.suxin.oci.mapper.other"},
        sqlSessionTemplateRef = "supplyStatisticsSqlSessionTemplate")
public class SupplyStatisticsDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "supply.datasource")
    public HikariConfig hikariConfig() {
        return new HikariConfig();
    }

    @Bean
    public DataSource supplyStatisticsDataSource() {
        return new HikariDataSource(hikariConfig());
    }

    @Bean
    public SqlSessionFactory supplyStatisticsSqlSessionFactory(@Qualifier(value = "supplyStatisticsDataSource")
                                                       DataSource supplyStatisticsDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(supplyStatisticsDataSource);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "supplyStatisticsTransactionManager")
    public PlatformTransactionManager platformTransactionManager(
            @Qualifier(value = "supplyStatisticsDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate supplyStatisticsSqlSessionTemplate(
            @Qualifier(value = "supplyStatisticsSqlSessionFactory") SqlSessionFactory supplyStatisticsSqlSessionFactory) {
        return new SqlSessionTemplate(supplyStatisticsSqlSessionFactory);
    }

}